package org.linitly.boot.base.utils.auth.strategy;

import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.linitly.boot.base.enums.ResultEnum;
import org.linitly.boot.base.exception.CommonException;
import org.linitly.boot.base.utils.bean.SpringBeanUtil;
import org.linitly.boot.base.utils.jwt.AbstractJwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: linitly
 * @date: 2021/5/24 14:09
 * @descrption: 单token模式，会自动过期
 */
public class SingleTokenExpireModule extends SingleTokenModule {

    private static volatile SingleTokenExpireModule singleTokenExpireModule;

    private SingleTokenExpireModule(AbstractJwtUtil jwtUtil) {
        super(jwtUtil);
    }

    public static SingleTokenExpireModule getInstance(AbstractJwtUtil jwtUtil) {
        if (singleTokenExpireModule == null) {
            synchronized (SingleTokenExpireModule.class) {
                if (singleTokenExpireModule == null) {
                    singleTokenExpireModule = new SingleTokenExpireModule(jwtUtil);
                }
            }
        }
        return singleTokenExpireModule;
    }

    @Override
    public void interceptorValid(String tokenResponseHeadKey) {
        HttpServletRequest request = SpringBeanUtil.getRequest();
        String token = jwtUtil.getToken(request);
        if (StringUtils.isBlank(token)) {
            throw new CommonException(ResultEnum.UNAUTHORIZED);
        }
        try {
            jwtUtil.parseToken(token);
        } catch (ExpiredJwtException e) {
            // token本身的过期不需处理
        }
        validToken(token);
        // 更新缓存中的token的过期时间
        auth.expireRedisToken(jwtUtil.getUserId(request));
    }

    @Override
    public void validExpiredToken(String token) {

    }

    @Override
    public void generateNewToken(String tokenResponseHeadKey) {

    }
}
